<template>
    <div class="login-template" :style="bgStyle">
        <div class="login-container">
            <h3 class="title">
                {{ settingStore.getName }}
            </h3>
            <a-form :model="formState" autocomplete="off" @finish="handleFinish">
                <a-form-item name="username" :rules="rules.username">
                    <a-input v-model:value="formState.username" placeholder="请输入用户名" size="large" :maxlength="100">
                        <template #prefix>
                            <user-outlined class="icon" />
                        </template>
                    </a-input>
                </a-form-item>
                <a-form-item name="password" :rules="rules.password">
                    <a-input-password v-model:value="formState.password" placeholder="请输入密码" size="large" :maxlength="100">
                        <template #prefix>
                            <lock-outlined class="icon" />
                        </template>
                    </a-input-password>
                </a-form-item>
                <a-form-item name="captcha" :rules="rules.captcha">
                    <a-input v-model:value="formState.captcha" placeholder="请输入验证码" size="large" :maxlength="4">
                        <template #prefix>
                            <safety-outlined class="icon" />
                        </template>
                        <template #addonAfter>
                            <img v-if="imgBase64" class="img" :src="imgBase64" @click="handleCaptcha" />
                        </template>
                    </a-input>
                </a-form-item>
                <a-checkbox v-model:checked="remember">记住密码</a-checkbox>
                <a-form-item>
                    <a-button class="login-btn" type="primary" html-type="submit" size="large">
                        <template v-if="loading" #icon>
                            <LoadingOutlined />
                        </template>
                        {{ loading ? '登录中...' : '登录' }}
                    </a-button>
                </a-form-item>
            </a-form>
        </div>
    </div>
</template>
<script setup>
import { reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { UserOutlined, LockOutlined, SafetyOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { getCaptcha, login } from '/@/api/Iframe/login.js'
import { SUCCESS_CODE } from '@iframe/tools/axios/axios'
import { PasswordRegular } from '@iframe/tools/utils/regular'
import { useTokenStore } from '@iframe/tools/store/modules/token'
import { useUserinfoStore } from '@iframe/tools/store/modules/userinfo'
import { useSettingStore } from '@iframe/tools/store/modules/setting'
import { usePermissionStore } from '@iframe/tools/store/modules/permission'
import { useTabsStore } from '@iframe/tools/store/modules/tabs'
import { putSession, getSession, removeSession } from '@iframe/tools/utils/SessionUtils'
import { LOGIN_INFO } from '@iframe/tools/config/SystemConfig'
import { getSetting } from '/@/api/Iframe/Setting'
import { notice } from '@iframe/tools/components'

const tokenStore = useTokenStore()
const tabsStore = useTabsStore()
const userinfoStore = useUserinfoStore()
const settingStore = useSettingStore()
const permissionStore = usePermissionStore()

const router = useRouter()

let imgBase64 = ref('')
const remember = ref(false)
const loading = ref(false)

const formState = reactive({ username: '', password: '', captcha: '', checkKey: '' })
const rules = reactive({
    username: [{ required: true, message: '请输入用户名' }],
    password: [
        { required: true, message: '请输入密码' },
        { pattern: PasswordRegular, message: '密码必须以字母开头，包括数字的8-20位字符串' }
    ],
    captcha: [{ required: true, message: '请输入验证码' }]
})

const bgStyle = computed(() => {
    return { backgroundImage: "url('" + `/api/${import.meta.env.IFRAME_CONTEXT_PATH}/sys/project/background` + "')" }
})

tokenStore.clearToken()
userinfoStore.clearUserinfo()
tabsStore.clear()
permissionStore.clear()
const loginString = getSession(LOGIN_INFO)

if (loginString) {
    const loginInfo = JSON.parse(loginString)
    remember.value = loginInfo.remember
    if (loginInfo.remember) {
        formState.username = loginInfo.username
        formState.password = loginInfo.password
    }
}
const handleCaptcha = () => {
    getCaptcha({ key: formState.checkKey }).then(result => {
        if (result.code === SUCCESS_CODE) {
            formState.checkKey = result.data.uuid
            imgBase64.value = result.data.img
        }
    })
}
handleCaptcha()

const loadSetting = () => {
    getSetting().then(result => {
        if (result.code === SUCCESS_CODE) {
            settingStore.setSetting(result.data)
        }
    })
}

const handleFinish = () => {
    if (remember.value === true) {
        putSession(LOGIN_INFO, JSON.stringify({ remember: remember.value, username: formState.username, password: formState.password }))
    } else {
        removeSession(LOGIN_INFO)
    }
    if (loading.value) {
        return
    }
    loading.value = true
    login(formState)
        .then(result => {
            if (result.code === SUCCESS_CODE) {
                tokenStore.setToken(result.data.token)
                userinfoStore.setUserinfo({
                    id: result.data.sysUser.id,
                    username: result.data.sysUser.username,
                    realname: result.data.sysUser.realname,
                    sysRoleId: result.data.sysUser.sysRoleId,
                    avatar: result.data.sysUser.avatar,
                    sysDepartId: result.data.sysUser.sysDepartId
                })
                router.push(import.meta.env.IFRAME_HOME_URL)
            } else if (result.code === 11000 || result.code === 12000) {
                notice.warning(result.message)
                formState.captcha = ''
                handleCaptcha()
            }
            loading.value = false
        })
        .catch(err => {
            loading.value = false
            console.error(err)
        })
}
loadSetting()
</script>
<style lang="less" scoped>
.login-template {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
    background-repeat: no-repeat;
    background-size: 100% 100%;

    .login-container {
        border-radius: 6px;
        background-image: url('/@/assets/image/login/input-bg.png');
        position: absolute;
        right: 250px;
        width: 490px;
        height: 450px;
        top: 50%;
        margin-top: -225px;
        padding: 45px 50px 0;

        .title {
            margin: 0 auto 30px auto;
            text-align: center;
            width: 100%;
            height: 40px;
            line-height: 40px;
            font-size: 25px;
            font-weight: bold;
            color: #3360c2;
        }

        .icon {
            color: rgba(0, 0, 0, 0.25);
        }

        .img {
            cursor: pointer;
        }

        :deep(.ant-input-group-addon) {
            border: none;
            background-color: transparent;
        }
        :deep(.ant-checkbox-wrapper-checked) {
            color: #1890ff;
        }
    }

    .login-btn {
        margin-top: 30px;
        width: 100%;
    }
}
</style>
